﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

using SmlEngine.Sprites.Base;

namespace SmlEngine.Sprites.Settings
{
    public class BackgroundSettings
    {
        private static Dictionary<int, BackgroundLayer> layers;

        private static BackgroundLayer current;
        private static float xSpeed;

        private static bool isLoaded;

        public static void Load(ContentManager content, Stream data)
        {
            if (!isLoaded)
            {
                layers = new Dictionary<int, BackgroundLayer>();

                int index = 0, settingIndex = 0;
                StringBuilder builder = new StringBuilder();

                for (int i = 0; i < data.Length; i++)
                {
                    char value = (char)data.ReadByte();

                    if (value == ':') //Reached the next item
                    {
                        layers.Add(index, current);
                        builder.Clear();
                        index++;
                        settingIndex = 0;
                    }
                    else if (value == ',')
                    {
                        ParseLayer(settingIndex, builder.ToString(), content);
                        settingIndex++;
                        builder.Clear();
                    }
                    else if (value != '\r' && value != '\n')
                    {
                        builder.Append(value);
                    }
                }

                isLoaded = true;
            }
        }

        private static void ParseLayer(int index, string value, ContentManager content)
        {
            switch(index)
            {
                case 0:
                    current = new BackgroundLayer();
                    current.Graphics = content.Load<Texture2D>(value);
                    return;

                case 1:
                    xSpeed = Convert.ToSingle(value);
                    return;

                case 2:
                    current.ScrollSpeed = new Vector2(xSpeed, Convert.ToSingle(value));
                    return;

                case 3:
                    current.ScrollType = (ScrollType)Convert.ToInt32(value);
                    return;
            }
        }

        public static BackgroundLayer GetBehaviour(int index)
        {
            return layers[index];
        }
    }
}
